<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card>
      <el-form ref="formRef" :model="searchForm" size="default" style="height: 30px;">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="searchForm.configName" placeholder="请输入配置名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="同步频率">
              <el-select v-model="searchForm.syncFrequency" placeholder="请选择同步频率">
                <el-option v-for="item in syncFrequencyOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="mt-2">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addBasicSiteInfoShow"
            v-hasPermi="['system:post:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['system:post:edit']">修改</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['system:post:remove']">删除</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['system:post:export']">导出</el-button>
          </el-col> -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <!-- 同步任务列表 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
        <el-table-column prop="configName" label="配置名称" align="center"></el-table-column>
        <el-table-column prop="syncFrequency" label="同步频率" align="center"></el-table-column>
        <el-table-column prop="lastSyncTime" label="上次同步时间" align="center"></el-table-column>
        <el-table-column prop="nextSyncTime" label="下次同步时间" align="center"></el-table-column>
        <el-table-column prop="status" label="配置状态" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="400">
          <template #default="scope">
            <el-button type="text" icon="More"  @click="handleDetail(scope.row)">查看详情</el-button>
            <el-button type="text" icon="Edit"  @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" icon="Delete"  @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" icon="CircleCheck" @click="handleStart(scope.row)">启动同步</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination background layout="prev, pager, next, jumper, total" :total="totalItems"
          v-model:current-page="currentPage" v-model:page-size="pageSize" @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>
  </div>

  <!-- 新增/修改同步任务对话框（保持不变） -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width: 500px;" destroy-on-close>
    <el-form ref="syncFormRef" :model="syncForm" label-width="120px" :rules="rules" style="width: 100%;">
      <!-- 配置名称 -->
      <el-form-item label="配置名称" prop="configName">
        <el-input v-model="syncForm.configName" placeholder="请输入同步任务配置名称" maxlength="50"></el-input>
      </el-form-item>

      <!-- 同步频率 -->
      <el-form-item label="同步频率" prop="syncFrequency">
        <el-select v-model="syncForm.syncFrequency" placeholder="请选择同步频率" clearable>
          <el-option label="每天" value="每天"></el-option>
          <el-option label="每周" value="每周"></el-option>
          <el-option label="每月" value="每月"></el-option>
        </el-select>
      </el-form-item>

      <!-- 配置状态 -->
      <el-form-item label="配置状态" prop="status">
        <el-select v-model="syncForm.status" placeholder="请选择配置状态">
          <el-option label="启用" value="启用"></el-option>
          <el-option label="禁用" value="禁用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上次同步时间" prop="lastSyncTime">
        <el-date-picker v-model="syncForm.lastSyncTime" type="datetime" placeholder="选择上次同步时间"
          value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item label="下次同步时间" prop="nextSyncTime">
        <el-date-picker v-model="syncForm.nextSyncTime" type="datetime" placeholder="选择下次同步时间"
          value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 查看详情对话框 -->
  <el-dialog title="同步任务详情" v-model="detailVisible" style="width: 1200px;" destroy-on-close>
    <el-table :data="detailForm" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="同步任务ID" align="center"></el-table-column>
      <el-table-column prop="syncConfigId" label="同步配置ID" align="center"></el-table-column>
      <el-table-column prop="taskType" label="同步类型" align="center"></el-table-column>
      <el-table-column prop="status" label="同步任务状态" align="center"></el-table-column>
      <el-table-column prop="startTime" label="同步任务开始时间" align="center"></el-table-column>
      <el-table-column prop="endTime" label="同步任务结束时间" align="center"></el-table-column>
      <el-table-column prop="failureReason" label="失败原因" align="center"></el-table-column>
      <el-table-column prop="retryCount" label="重试次数" align="center"></el-table-column>
      <el-table-column prop="syncScope" label="同步范围" align="center"></el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 启动同步对话框（新增taskType字段） -->
  <el-dialog title="启动同步" v-model="startSyncVisible" style="width: 500px;" destroy-on-close>
    <el-form ref="startSyncFormRef" :model="startSyncForm" label-width="120px" :rules="startSyncRules"
      style="width: 100%;">
      <!-- 同步配置ID -->
      <el-form-item label="同步配置ID" prop="configId">
        <el-input v-model="startSyncForm.configId" disabled></el-input>
      </el-form-item>

      <!-- 同步类型（新增） -->
      <el-form-item label="同步类型" prop="taskType">
        <el-select v-model="startSyncForm.taskType" placeholder="请选择同步类型">
          <el-option label="全量同步" value="全量同步"></el-option>
          <el-option label="增量同步" value="增量同步"></el-option>
        </el-select>
      </el-form-item>

      <!-- 同步范围 -->
      <el-form-item label="同步范围" prop="syncScope">
        <el-select v-model="startSyncForm.syncScope" placeholder="请选择同步范围">
          <el-option label="全量" value="全量"></el-option>
          <el-option label="指定组织" value="指定组织"></el-option>
        </el-select>
      </el-form-item>

      <!-- 指定组织ID（仅同步范围为指定组织时显示） -->
      <el-form-item label="指定组织ID" prop="orgIds" v-if="startSyncForm.syncScope === '指定组织'">
        <el-input v-model="startSyncForm.orgIdsStr" placeholder="请输入组织ID，多个用逗号分隔"></el-input>
        <div class="form-hint">提示：多个组织ID用英文逗号分隔，如 1,2,3</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="startSyncVisible = false">取消</el-button>
      <el-button type="primary" @click="submitStartSync">确认启动</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listSyncConfig,
  addSyncConfig,
  updateSyncConfig,
  detailSyncConfig,
  deleteSyncConfig,
  startSync,
  getDetailTable
} from '../../../api/system/sync_manage';

// 原有变量保持不变
// 对话框核心配置
const dialogVisible = ref(false);
const syncFormRef = ref(null);
const dialogLoading = ref(false);

// 表单数据
const syncForm = reactive({
  id: '',
  configName: '',
  syncFrequency: '',
  customFrequency: '',
  status: '启用',
  firstSyncTime: '',
});

const ids = ref([])
const names = ref([])
const single = ref(true);
const multiple = ref(true);
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  names.value = selection.map(item => item.configName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 表单验证规则
const rules = {
  configName: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { max: 50, message: '配置名称不能超过50个字符', trigger: 'blur' }
  ],
  syncFrequency: [
    { required: true, message: '请选择同步频率', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择配置状态', trigger: 'change' }
  ],
  nextSyncTime: [
    { required: true, message: '请选择下次同步时间', trigger: 'change' }
  ],
  lastSyncTime: [
    { required: true, message: '请选择上次同步时间', trigger: 'change' }
  ]
};

// 对话框标题
const dialogTitle = computed(() => {
  return syncForm.id ? '修改同步任务' : '新增同步任务';
});

// 查看详情相关
const detailVisible = ref(false);
// const detailForm = reactive({});
const detailForm = ref();
const handleDetail = async (row) => {
  try {
    const response = await getDetailTable(row.id);
    if (response.code === 200) {
      // Object.assign(detailForm, response.data);
      detailForm.value = response.data
      detailVisible.value = true;
    } else {
      ElMessage.error('获取详情失败：' + response.msg);
    }
  } catch (error) {
    console.error('获取详情失败：', error);
    ElMessage.error('获取详情失败，请重试');
  }
};

// 启动同步相关
const startSyncVisible = ref(false);
const startSyncFormRef = ref(null);
const startSyncForm = reactive({
  configId: '',       // 同步配置ID
  taskType: '',       // 同步类型（新增字段）
  syncScope: '',      // 同步范围
  orgIdsStr: ''       // 组织ID字符串（用于输入）
});

// 启动同步验证规则（包含新增的taskType验证）
const startSyncRules = {
  configId: [
    { required: true, message: '同步配置ID不能为空', trigger: 'blur' }
  ],
  taskType: [          // 新增taskType验证
    { required: true, message: '请选择同步类型', trigger: 'change' }
  ],
  syncScope: [
    { required: true, message: '请选择同步范围', trigger: 'change' }
  ],
  orgIds: [
    {
      required: (rule, value, callback) => {
        if (startSyncForm.syncScope === '指定组织' && !startSyncForm.orgIdsStr) {
          return callback(new Error('请输入指定组织ID'));
        }
        callback();
      },
      trigger: 'blur'
    }
  ]
};

// 打开启动同步对话框
const handleStart = (row) => {
  // 重置表单
  startSyncForm.configId = Number(row.id);
  startSyncForm.taskType = '';
  startSyncForm.syncScope = '';
  startSyncForm.orgIdsStr = '';
  startSyncVisible.value = true;
  // 重置验证状态
  setTimeout(() => {
    startSyncFormRef.value?.clearValidate();
  }, 0);
};

// 提交启动同步
const submitStartSync = async () => {
  if (!startSyncFormRef.value) return;

  try {
    // 表单验证
    await startSyncFormRef.value.validate();

    // 处理组织ID（转换为integer数组）
    let orgIds = [];
    if (startSyncForm.syncScope === '指定组织' && startSyncForm.orgIdsStr) {
      orgIds = startSyncForm.orgIdsStr.split(',').map(id => parseInt(id, 10)).filter(id => !isNaN(id));
    }

    // 构造请求参数
    const params = {
      configId: startSyncForm.configId,
      taskType: startSyncForm.taskType,       // 新增同步类型参数
      syncScope: startSyncForm.syncScope,
      orgIds: orgIds.length > 0 ? orgIds : undefined
    };

    // 调用启动同步接口
    await startSync(params);
    ElMessage.success('同步已启动');
    startSyncVisible.value = false;
    getTableData(); // 刷新表格
  } catch (error) {
    console.error('启动同步失败：', error);
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.msg || '启动同步失败，请重试');
    }
  }
};

// 原有函数保持不变
const openAddDialog = () => {
  resetForm();
  dialogVisible.value = true;
  setTimeout(() => {
    syncFormRef.value?.clearValidate();
  }, 0);
};

const openEditDialog = async (id) => {
  try {
    dialogLoading.value = true;
    resetForm();
    const response = await detailSyncConfig(id);
    if (response.code === 200) {
      Object.assign(syncForm, response.data);
      dialogVisible.value = true;
      setTimeout(() => {
        syncFormRef.value?.clearValidate();
      }, 0);
    } else {
      ElMessage.error('获取详情失败：' + response.msg);
    }
  } catch (error) {
    console.error('获取详情失败：', error);
    ElMessage.error('获取详情失败，请重试');
  } finally {
    dialogLoading.value = false;
  }
};

const resetForm = () => {
  syncForm.id = '';
  syncForm.configName = '';
  syncForm.syncFrequency = '';
  syncForm.customFrequency = '';
  syncForm.status = '启用';
  syncForm.nextSyncTime = '';
  syncForm.lastSyncTime = '';
  syncFormRef.value?.resetFields();
};

const handleCancel = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  if (!syncFormRef.value) return;

  try {
    await syncFormRef.value.validate();
    dialogLoading.value = true;

    if (syncForm.id) {
      await updateSyncConfig(syncForm.id, syncForm);
      ElMessage.success('修改成功');
    } else {
      await addSyncConfig(syncForm);
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    resetForm();
    getTableData();
  } catch (error) {
    console.error('操作失败：', error);
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.msg || '操作失败，请重试');
    }
  } finally {
    dialogLoading.value = false;
  }
};

const syncFrequencyOptions = [
  { label: '全部', value: '' },
  { label: '每天', value: '每天' },
  { label: '每周', value: '每周' },
  { label: '每月', value: '每月' }
];

const searchForm = ref({
  configName: '',
  syncFrequency: ''
});

const tableData = ref([]);
const loading = ref(false);
const totalItems = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const getTableData = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      configName: searchForm.value.configName,
      syncFrequency: searchForm.value.syncFrequency
    };

    const response = await listSyncConfig(params);
    if (response.code === 200) {
      tableData.value = response.data || [];
      totalItems.value = response.data.total || 0;
    } else {
      ElMessage.error('获取数据失败: ' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('获取同步配置列表失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getTableData();
});

const handleSearch = () => {
  currentPage.value = 1;
  getTableData();
};

const handleReset = () => {
  searchForm.value = {
    configName: '',
    syncFrequency: ''
  };
  currentPage.value = 1;
  getTableData();
};

const addBasicSiteInfoShow = () => {
  openAddDialog();
};

const handleEdit = (row) => {
  openEditDialog(row.id);
};


const handleDelete = (row) => {
  const syncIds = row.id || ids.value;
  ElMessageBox.confirm(`确定要删除配置名称为${row.configName}的数据项？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSyncConfig(row.id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (error) {
      ElMessage.error(error.msg || '删除失败');
    }
  });
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  getTableData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  getTableData();
};
</script>

<style scoped>
:deep(.el-form-item) {
  margin-bottom: 15px;
}

:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-loading-parent--relative) {
  position: relative;
}

/* 新增提示文字样式 */
.form-hint {
  color: #606266;
  font-size: 12px;
  margin-top: 5px;
}
</style>